namespace Stee.CAP8.MessageBus.Sagas.Core.Storages.Dtos
{
    using System;
    using System.Collections.Concurrent;
    using Stee.CAP8.MessageBus.Sagas.Core.Storages.Enums;

    /// <summary>
    /// 当前saga的执行状态
    /// </summary>
    public class SagaProcessHistory
    {
        public string Sagaid { get; set; }

        public SagaProcessState ProcessStatus { get; set; }

        public DateTime TimeStamp { get; set; }

    }

    public interface ISagaProcessHistoryStorage
    {
        void Save(string sagaId, SagaProcessHistory sagaProcess);

        SagaProcessHistory GetTheLatestStatus(string sagaId);


    }

    public class InMemorySagaProcessHistoryRepository : ISagaProcessHistoryStorage
    {
        private static ConcurrentDictionary<string, SagaProcessHistory> HistoryList = new ConcurrentDictionary<string, SagaProcessHistory>();
        public SagaProcessHistory GetTheLatestStatus(string sagaId)
        {
            if (!HistoryList.TryGetValue(sagaId, out var latestStatus))
            {
                return null;
            }
            return latestStatus;

        }

        public void Save(string sagaId, SagaProcessHistory sagaProcess)
        {
            HistoryList.AddOrUpdate(sagaId, sagaProcess, (k, v) => v);
        }
    }
}
